#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/InetAddress.h>
#include <muduo/net/Buffer.h>
#include <muduo/base/CountDownLatch.h>
#include <iostream>
#include <memory>
#include <string>

class DictClient
{

public:
    DictClient(const std::string &sip, int sport) :
        _baseloop(_threadloop.startLoop()),
        _countdown(1),
        _client(_baseloop, muduo::net::InetAddress(sip, sport), "DictClient")
    {
        // 注册函数
        _client.setConnectionCallback(std::bind(&DictClient::OnConnection, this, std::placeholders::_1));

        _client.setMessageCallback(std::bind(&DictClient::OnMessage, this,
                                             std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        // 连接服务器
        _client.connect();
        _countdown.wait();
    }
    bool send(const std::string &msg)
    {
        if (_conn->connected() == false)
        {
            std::cout << "连接断开" << std::endl;
            return false;
        }
        _conn->send(msg);
        return true;
    }

private:
    // 设置回调函数
    // 1.连接管理
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            std::cout << "连接成功" << std::endl;
            _countdown.countDown(); // 计数--，为0时自动激活 count--
            _conn = conn;
        }
        else
        {
            std::cout << "连接断开" << std::endl;
            _conn.reset();
        }
    }
    // 2.信息管理
    void OnMessage(const muduo::net::TcpConnectionPtr &conn,
                   muduo::net::Buffer *buf, muduo::Timestamp)
    {
        std::string res = buf->retrieveAllAsString();
        std::cout << "client :" << res << std::endl;
    }

private:
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _countdown;
    muduo::net::EventLoopThread _threadloop;
    muduo::net::EventLoop *_baseloop;
    muduo::net::TcpClient _client;
};
int main()
{
    DictClient client("127.0.0.1", 8888);
        while(1) {
        std::string msg;
        std::cin >> msg;
        client.send(msg);
    }

    return 0;
}